package com.cnplan.core;

import com.cnplan.entity.ArcRollImage;
import com.cnplan.service.ArcRollImageService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class KUtil {
    private static final String httpUrl="";//线上使用 http://192.168.6.90:8080

    private ArcRollImageService arcRollImageService;
    public KUtil(ArcRollImageService arcRollImageService){
        this.arcRollImageService=arcRollImageService;
    }

    public static String daoHangT1(String type){
        String retStr="";
        switch (type){
            case "fin":
                retStr= "竣工档案";
                break;
            case "plan":
                retStr= "规划档案";
                break;
            case "check":
                retStr= "规划验收档案";
                break;
            case "land":
                retStr= "土地管理档案";
                break;
            case "earth":
                retStr= "用地档案";
                break;
            case "lic":
                retStr= "执照档案";
                break;
            case "punish":
                retStr= "规划处罚档案";
                break;
        }
        return retStr;
    }

    public static void imageDirectory(String url, Set pathList){
        File file=new File(url);
        File[] listFile=file.listFiles();
        for (File fileA:listFile) {
            if(fileA.isDirectory()){
                imageDirectory(fileA.getPath(),pathList);
            }else{
                pathList.add(file.getPath());
            }
        }
    }

    /**
     * 对比数据库tif地址并记录
     */
    public void imagePath(){
        Set<String> set=new HashSet();
        imageDirectory("F://tif",set);
        for (int i = 1; i >0 ; i++) {
            PageInfo pageInfo=arcRollImageService.findByAllRollImageList(i+"","500");
            if (pageInfo.getSize()==0){
                break;
            }else {
                List<ArcRollImage> arcRollImageList=pageInfo.getList();
                for (ArcRollImage arcRollImage:arcRollImageList){
                    String[] strArray=arcRollImage.getPath().split("\\\\");
                    int lastName=arcRollImage.getPath().lastIndexOf("\\");
                    String projectName=arcRollImage.getPath().substring(0,lastName);
                    boolean boo=true;
                    for (String st:set){
                        if(st.contains(projectName)){
                            boo=false;
                            arcRollImageService.updateRollImageURl(arcRollImage.getId(),
                                    st.substring(1)+arcRollImage.getPath().substring(lastName));
                            System.out.println(st.substring(1)+arcRollImage.getPath().substring(lastName));
                            break;
                        }
                    }
                    if(boo){
                        projectName=strArray[strArray.length-2];
                        for (String st:set){
                            if(st.contains(projectName)){
                                arcRollImageService.updateRollImageURl(arcRollImage.getId(),
                                        st.substring(2)+arcRollImage.getPath().substring(lastName));
                                System.out.println(st.substring(2)+arcRollImage.getPath().substring(lastName));
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 查询tif生成数量并记录
     */
    public void imageNum(){
        for (int i = 1; i >0 ; i++) {
            PageInfo pageInfo=arcRollImageService.findByAllRollImageList(i+"","500");
            if (pageInfo.getSize()==0){
                break;
            }else {
                List<ArcRollImage> arcRollImageList=pageInfo.getList();
                for (ArcRollImage arcRollImage:arcRollImageList){
                    String urlStr="d:"+arcRollImage.getImageUrl();
                    String url=urlStr.replace("\\tif","\\tifjpg");
                    File file=new File(url);
                    File[] listFile=file.listFiles();
                    arcRollImageService.updateRollImageNum(arcRollImage.getId(),listFile==null?null:listFile.length+"");
                }
            }
        }
        System.out.println("--------------");
    }



    /**
     * 批量制作缩略图
     * */
    public static void imageSLT(String url) {
        File file=new File(url);
        File[] listFile=file.listFiles();
        try {
            for (File fileA:listFile) {
                if(fileA.isDirectory()){
                    imageSLT(fileA.getPath());
                }else{
                    if (fileA.getPath().contains(".tif")) {
                        String tifsltpath=fileA.getPath().substring(0,fileA.getPath().lastIndexOf("."));
                        String tifsltpatht=tifsltpath.replace("\\tif", "\\tifjpg");
                        File file1=new File(tifsltpatht);
                        if(!file1.exists()){
                            tiffToJPEGByImagedataIO(fileA.getPath());
                        }
                    }
                }


            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        //String[] rulArray= {"D://tif/jg","D:/tif/punish","D://tif/tdgl","D://tif/wt_jg","D://tif/yd","D://tif/zz"};
        String[] rulArray= {"F://tif/jg","F:/tif/punish","F://tif/tdgl","F://tif/wt_jg","F://tif/yd","F://tif/zz"};
        for (int i=0;i<rulArray.length;i++) {
            System.out.println("rulArray[i]---"+rulArray[i]);
            new CreatrTifGifThread(rulArray[i]).start();
        }
//        imageSLT("d://tif");
//        tif2Jpg("c:/183864a7-50a1-465a-82bd-d63b13460fbf.tif");
//        tiffToJPEGByImageIO("c:/183864a7-50a1-465a-82bd-d63b13460fbf.tif");
//        tiffToJPEGByImageIO("c:/29de80cb-0c4d-4176-91da-03c2deb64a7b.tif");

    }
    //批量将缩略图转jpg
    private static void tiffToJPEGByImagedataIO(String tiff) throws IOException {
        ImageInputStream input = null;
        ImageReader reader = null;
        try {
            //以图片输入流形式读取到tif
            input = ImageIO.createImageInputStream(new File(tiff));
            // Get the reader
            //获得image阅读器，阅读对象为tif文件转换的流
            reader = ImageIO.getImageReaders(input).next();
            String path,tiffName,tifsltPath;
            path = tiff.substring(0, tiff.lastIndexOf("."));
            tifsltPath=path.replace("\\tif", "\\tifjpg");

            reader.setInput(input);
            //tif文件页数
            int count = reader.getNumImages(true);
            //取得第i页
            for (int i=0;i<count;i++){
                BufferedImage image = reader.read(0, null);
                File f = new File(tifsltPath,"\\"+i+".jpg");
                System.out.println(tifsltPath);
                try {
                    if(!f.exists()){
                        f.getParentFile().mkdirs();
                        f.createNewFile();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ImageIO.write(image, "JPEG", f);

            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            reader.dispose();
            input.close();
        }
    }

    //批量跑缩略图
    private static void tiffToJPEGByImageIO(String tiff) {
        ImageInputStream input;
        try {
            //以图片输入流形式读取到tif
            input = ImageIO.createImageInputStream(new File(tiff));
            // Get the reader
            //获得image阅读器，阅读对象为tif文件转换的流
            ImageReader reader = ImageIO.getImageReaders(input).next();
            String path,tiffName,tifsltPath;
            path = tiff.substring(0, tiff.lastIndexOf("."));
            tifsltPath=path.replace("\\tif", "\\tifslt");
            try {
                reader.setInput(input);
                //tif文件页数
                int count = reader.getNumImages(true);
                System.out.println(reader.getFormatName());
                //取得第i页
                BufferedImage image = reader.read(0, null);
                File f = new File(tifsltPath,"\\"+0+".jpg");
                try {
                    if(!f.exists()){
                        f.getParentFile().mkdirs();
                        f.createNewFile();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                int w = image.getWidth();
                int h = image.getHeight();
                BufferedImage dimg = new BufferedImage(100, 60, BufferedImage.TYPE_3BYTE_BGR);
                Graphics2D g = dimg.createGraphics();
                g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g.drawImage(image, 0, 0, 100, 60, 0, 0, w, h, null);
                g.dispose();
                //保存图片
                ImageIO.write(dimg, "jpg", f);
//                    ImageIO.write(image, "JPEG", f);

//                }
            }
            finally {
                reader.dispose();
                input.close();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    public InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setConnectTimeout(10 * 1000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断字符串中是否包含中文
     * @param str
     * 待校验字符串
     * @return 是否为中文
     * @warn 不能校验是否为中文标点符号
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    public static String encode(String url) {
        try {

            Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
            int count = 0;
            while (matcher.find()) {
                //System.out.println(matcher.group());
                String tmp=matcher.group();
                url=url.replaceAll(tmp,java.net.URLEncoder.encode(tmp,"utf-8"));
            }
            // System.out.println(count);
            //url = java.net.URLEncoder.encode(url,"gbk");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return url;
    }
}
